#include "global_var.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "MindVision.h"
#include "CameraApi.h"
#include "CameraDefine.h"
#include "CameraStatus.h"

#include <iostream>

#include <opencv2/opencv.hpp>

#include "energy.h"

#include "serial.h"

using namespace std;
using namespace cv;

int flag = 0;//判断串口是否已经初始化

Mat cv_img;
MindVision camera;
Energy energy;

/*******************串口通讯初始化*******************/
Serialport serp("/dev/ttyUSB0");

/*******************串口通讯初始化*******************/

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui -> setupUi(this);
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()),this, SLOT(readFrame()) );
    initMainWindow();
}

MainWindow::~MainWindow()
{
    if(flag == 0){
        serp.set_opt(115200, 8, 'N', 1);
        flag++;//保证串口只初始化一次
    }
    delete ui;
}



void MainWindow::initMainWindow()
//加入一些可能需要的窗口初始化方法
{
    //connect(&theTimer, &QTimer::timeout, this, &MainWindow::updateImage);

    //QString imgPath = "D:\\Qt\\imgproc\\girldiver.jpg"; //路径中不能含中文字符
    //QString imgPath = "/home/bubing3/Documents/new_evr/try/1.jpeg";                  //本地路径（图片直接存放在项目目录下）
    //Mat imgData = imread(imgPath.toLatin1().data());    //读取图像数据
    //myImg = cv_img;
    //Mat imgData = imread(imgPath.toLatin1().data());    //读取图像数据
    //myImg = cv_img;
    //myQImg = QImage((const unsigned char*)(cv_img.data), cv_img.cols, cv_img.rows, QImage::Format_RGB888);
    //imgShow();

}
void MainWindow::on_openCamera_clicked()
{
    camera.open();
    timer -> start(33);
}

void MainWindow::on_closeCamera_clicked()
{
    timer -> stop();
    cv_img.release();
    ui -> viewLabel -> clear();
}

void MainWindow::imgProc()
{
        cvtColor(cv_img, cv_img, COLOR_BGR2RGB);
        //在此输入图像处理的函数
        extern Mat frame;
        extern vector<vector<Point>> Fans_contours;
        extern vector<Vec4i> Fans_hierarchy;
        extern vector<vector<Point>> Fans_contours_out1, Fans_contours_out2;
        extern double theta;
        extern int whereArea;

        energy.image_clear(cv_img);
        frame = cv_img;
        energy.Contours_out(frame, Fans_contours, Fans_hierarchy);
        energy.Theta_measurement(frame,Fans_contours_out1,Fans_contours_out2);

        int d = 10;

        Point center = Point(frame.cols / 2, frame.rows / 2);
        line( frame, Point( center.x - d, center.y - d), Point( center.x + d, center.y + d ), ( 0, 0, 0), 1, LINE_AA, 0);
        line( frame, Point( center.x + d, center.y - d), Point( center.x - d, center.y + d ), ( 0, 0, 0), 1, LINE_AA, 0);

        imshow("111", frame);

        if((theta >= horizon9 -5 && theta <= horizon9) || (theta >= horizon1 && theta <= horizon1 +5)){
            //目前位于位置1
            whereArea = 1;
            cout << "area = " << whereArea << endl;

        }
        else if(theta >= horizon2 - 5 && theta < horizon3 + 5){
            //目前位于位置2
            whereArea = 2;
            cout << "area = " << whereArea <<endl;

        }
        else if(theta >= horizon3 - 5 && theta < horizon4 + 5){
            //目前位于位置3
            whereArea = 3;
            cout << "area = " << whereArea << endl;

        }
        else if(theta >= horizon4 - 5 && theta < horizon5 + 5){
            //目前位于位置4
            whereArea = 4;
            cout << "area = " << whereArea << endl;

        }
        else if(theta >= horizon5 - 5 && theta < horizon6 + 5){
            //目前位于位置5
            whereArea = 5;
            cout << "area = " << whereArea << endl;

        }
        else if(theta >= horizon6 - 5 && theta < horizon7 + 5){
            //目前处于位置6
            cout << "area = " << whereArea << endl;

        }
        else if(theta >= horizon7 - 5 && theta < horizon8 + 5){
            //目前处于位置7
            whereArea = 7;
            cout << "area = " << whereArea << endl;

        }
        else if(theta >= horizon8 - 5 && theta < horizon9 + 5){
            //目前处于位置8
            whereArea = 8;
            cout << "area = "<< whereArea <<endl;

        }
        extern double kickAngle[8];
        cout << kickAngle[0] << endl;
        //需根据大符的旋转方向作出更改
        //if(abs( theta - )

        //图像处理到此结束

        myQImg = QImage((const unsigned char*)(frame.data), frame.cols, frame.rows, QImage::Format_RGB888);
        ui->viewLabel->setPixmap(QPixmap::fromImage(myQImg.scaled(ui->viewLabel->size(), Qt::KeepAspectRatio)));//在Qt界面上显示图像
        //readFrame();
        //this -> update();
}

void MainWindow::readFrame()
{
    camera.getImage(cv_img);
    //imshow("111",cv_img);
    imgProc();

}

/*void MainWindow::paintEvent(QPaintEvent *e){

    QImage image2 = QImage((const unsigned char*)(cv_img.data), cv_img.cols, cv_img.rows, QImage::Format_RGB888);
    ui->viewLabel->setPixmap(QPixmap::fromImage(image2.scaled(ui->viewLabel->size(), Qt::KeepAspectRatio)));//在Qt界面上显示图像
    //ui->viewLabel->resize(cv_img.size());
    ui->viewLabel->show();
}*/






void MainWindow::on_contrastVerticalSlider_valueChanged(int value)
{
    a = value;
}

void MainWindow::on_brightnessVerticalSlider_valueChanged(int value)
{
    b = value;
}

void MainWindow::on_pushButton_clicked()
{
    //当按下此按键后，摄像头中心因在炮口移动后指向能量机关圆心
    //会读取并处理200帧的图像
    int flag = 0;
    for(int i = 0; i<200 ;i++){
        readFrame();
        extern Mat frame;
        double xy[2];
        extern Point2f point_circle;
        Point2f frame_center = Point2f(frame.cols, frame.rows);
        xy[0] = frame_center.x - point_circle.x;//正值左转，负值右转
        xy[1] = frame_center.y - point_circle.y;
        if(abs(xy[0]) < 5 && abs(xy[1]) < 5){
            cout << "到达指定位置" << endl;
            flag++;
            break;
        }
        serp.sendXY(xy);
    }
    if(flag != 1){
        cout << "无法达到指定位置！请修改循环次数或调整镜头位置使能量机关圆心出现在镜头画面中" << endl;
    }

}
